package com.group.seckill.xxl;

import com.group.seckill.service.SeckillService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lins
 * @date 2021/11/15 8:55
 */
@Service
@Slf4j
public class SeckillScheduledXxl {
    @Autowired
    SeckillService seckillService;
    @Autowired
    RedissonClient redissonClient;

    private static final String SECKILL_LOCK = "seckill:lock";

    @XxlJob("uploadSeckillSession")
    public void uploadSeckillSession() {

        RLock lock = redissonClient.getLock(SECKILL_LOCK);
        lock.lock(10, TimeUnit.MILLISECONDS);
        try {
            log.info("上架秒杀商品");
            seckillService.uploadSeckillSession();
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
